#include "map.h"

int appShowSize = 0;

int createTextureFromSubSurface(SDL_Renderer* renderer, SDL_Surface* imageSurface, SDL_Rect cutRect, SDL_Texture** imageTexture) {

     // 创建指定尺寸
    SDL_Surface* subSurface = SDL_CreateRGBSurface(0, BLOCK_WIDTH, BLOCK_HEIGHT, imageSurface->format->BitsPerPixel,
                                                       imageSurface->format->Rmask, imageSurface->format->Gmask,
                                                       imageSurface->format->Bmask, imageSurface->format->Amask);
    if (subSurface == nullptr) {
        SDL_Log("Failed to create surface: %s", SDL_GetError());
        return -1;
    }

    // 复制一部分到新的表面(素材块的比例是32 * 32)
    SDL_BlitSurface(imageSurface, &cutRect, subSurface, nullptr);

    // 创建纹理
    *imageTexture = SDL_CreateTextureFromSurface(renderer, subSurface);
    if (imageTexture == nullptr) {
        SDL_Log("Failed to create texture: %s", SDL_GetError());
        SDL_FreeSurface(subSurface);
        return -2;
    }

    return 0;
}

int mapResource::initResource(SDL_Renderer* renderer)
{
    // 加载PNG图像
    SDL_Surface *icon2Surface = IMG_Load("tiled/icon2.png");
    if (icon2Surface == nullptr) {

        SDL_Log("Failed to load icon.png: %s", IMG_GetError());
    }

    SDL_Surface *mapSurface = IMG_Load("tiled/map.png");
    if (mapSurface == nullptr) {

        SDL_Log("Failed to load map.png: %s", IMG_GetError());
    }

    SDL_Surface *heroSurface = IMG_Load("tiled/hero.png");
    if (heroSurface == nullptr) {

        SDL_Log("Failed to load map.png: %s", IMG_GetError());
    }

    // 0 黄钥匙
    SDL_Rect yellowKeyPostion = { 0, 0, 32, 32 };
    SDL_Texture *yellowKeyTexture = nullptr;
    if (createTextureFromSubSurface(renderer, icon2Surface, yellowKeyPostion, &yellowKeyTexture) < 0) {

    }
    texture.push_back(yellowKeyTexture);

    // 1 蓝钥匙
    SDL_Rect blueKeyPostion = { 32, 0, 32, 32 };
    SDL_Texture *blueKeyTexture = nullptr;
    if (createTextureFromSubSurface(renderer, icon2Surface, blueKeyPostion, &blueKeyTexture) < 0) {

    }
    texture.push_back(blueKeyTexture);
    
    // 2 红钥匙
    SDL_Rect redKeyPostion = { 64, 0, 32, 32 };
    SDL_Texture *readKeyTexture = nullptr;
    if (createTextureFromSubSurface(renderer, icon2Surface, redKeyPostion, &readKeyTexture) < 0) {

    }
    texture.push_back(readKeyTexture);

    // 3 地面
    SDL_Rect groudPostion = { 0, 0, 32, 32 };
    SDL_Texture *groudTexture = nullptr;
    if (createTextureFromSubSurface(renderer, mapSurface, groudPostion, &groudTexture) < 0) {

    }
    texture.push_back(groudTexture);

    // 4 墙
    SDL_Rect wallPostion = { 32, 0, 32, 32 };
    SDL_Texture *wallTexture = nullptr;
    if (createTextureFromSubSurface(renderer, mapSurface, wallPostion, &wallTexture) < 0) {

    }
    texture.push_back(wallTexture);

    // 5 黄色的门
    SDL_Rect yellowDoorPostion = { 0, 64, 32, 32 };
    SDL_Texture *yellowDoorTexture = nullptr;
    if (createTextureFromSubSurface(renderer, mapSurface, yellowDoorPostion, &yellowDoorTexture) < 0) {

    }
    texture.push_back(yellowDoorTexture);

    // 6 蓝色的门
    SDL_Rect bludDoorPostion = { 32, 64, 32, 32 };
    SDL_Texture *blueDoorTexture = nullptr;
    if (createTextureFromSubSurface(renderer, mapSurface, bludDoorPostion, &blueDoorTexture) < 0) {

    }
    texture.push_back(blueDoorTexture);

    // 7 红色的门
    SDL_Rect redDoorPostion = { 64, 64, 32, 32 };
    SDL_Texture *redDoorTexture = nullptr;
    if (createTextureFromSubSurface(renderer, mapSurface, redDoorPostion, &redDoorTexture) < 0) {

    }
    texture.push_back(redDoorTexture);

    // 8 红宝石
    SDL_Rect redDiamondPostion = { 96, 32, 32, 32 };
    SDL_Texture *redDiamondTexture = nullptr;
    if (createTextureFromSubSurface(renderer, icon2Surface, redDiamondPostion, &redDiamondTexture) < 0) {

    }
    texture.push_back(redDiamondTexture);

    // 9 蓝宝石
    SDL_Rect blueDiamondPostion = { 64, 32, 32, 32 };
    SDL_Texture *blueDiamondTexture = nullptr;
    if (createTextureFromSubSurface(renderer, icon2Surface, blueDiamondPostion, &blueDiamondTexture) < 0) {

    }
    texture.push_back(blueDiamondTexture);

    // 10 绿宝石
    SDL_Rect greenDiamondPostion = { 0, 64, 32, 32 };
    SDL_Texture *greenDiamondTexture = nullptr;
    if (createTextureFromSubSurface(renderer, icon2Surface, greenDiamondPostion, &greenDiamondTexture) < 0) {

    }
    texture.push_back(greenDiamondTexture);

    // 11 红药水
    SDL_Rect redMedicineLiquidPostion = { 64, 64, 32, 32 };
    SDL_Texture *redMedicineLiquidTexture = nullptr;
    if (createTextureFromSubSurface(renderer, icon2Surface, redMedicineLiquidPostion, &redMedicineLiquidTexture) < 0) {

    }
    texture.push_back(redMedicineLiquidTexture);

    // 12 蓝药水
    SDL_Rect blueMedicineLiquidPostion = { 96, 64, 32, 32 };
    SDL_Texture *blueMedicineLiquidTexture = nullptr;
    if (createTextureFromSubSurface(renderer, icon2Surface, blueMedicineLiquidPostion, &blueMedicineLiquidTexture) < 0) {

    }
    texture.push_back(blueMedicineLiquidTexture);

    // 13 黄药水
    SDL_Rect yellowMedicineLiquidPostion = { 96, 96, 32, 32 };
    SDL_Texture *yellowMedicineLiquidTexture = nullptr;
    if (createTextureFromSubSurface(renderer, icon2Surface, yellowMedicineLiquidPostion, &yellowMedicineLiquidTexture) < 0) {

    }
    texture.push_back(yellowMedicineLiquidTexture);

    // 14 绿药水
    SDL_Rect greenMedicineLiquidPostion = { 96, 128, 32, 32 };
    SDL_Texture *greenMedicineLiquidTexture = nullptr;
    if (createTextureFromSubSurface(renderer, icon2Surface, greenMedicineLiquidPostion, &greenMedicineLiquidTexture) < 0) {

    }
    texture.push_back(greenMedicineLiquidTexture);

    // 15 人物
    SDL_Rect heroFront1Postion = { 0, 0, 32, 32 };
    SDL_Texture *heroFront1Texture = nullptr;
    if (createTextureFromSubSurface(renderer, heroSurface, heroFront1Postion, &heroFront1Texture) < 0) {

    }
    texture.push_back(heroFront1Texture);

    // 16 去上一层的楼梯
    SDL_Rect downStairPostion = { 0, 192, 32, 32 };
    SDL_Texture *downStairTexture = nullptr;
    if (createTextureFromSubSurface(renderer, mapSurface, downStairPostion, &downStairTexture) < 0) {

    }
    texture.push_back(downStairTexture);

    // 17 去下一层的楼梯
    SDL_Rect upStairPostion = { 32, 192, 32, 32 };
    SDL_Texture *upStairTexture = nullptr;
    if (createTextureFromSubSurface(renderer, mapSurface, upStairPostion, &upStairTexture) < 0) {

    }
    texture.push_back(upStairTexture);

    return 0;
}

int mapResource::isCollisions(SDL_Keycode keyCode) {

    int moveXPos = 0, moveYPos = 0;
    int itemId = -1;
    switch (keyCode)
    {
    case SDLK_UP:

        SDL_Log("up key pressed");
        // 获取移动之后的坐标
        moveXPos = xPos;
        moveYPos = yPos - appShowSize;
        
        break;
    case SDLK_DOWN:

        SDL_Log("down key pressed");
        moveXPos = xPos;
        moveYPos = yPos + appShowSize;

        break;
    case SDLK_LEFT:

        SDL_Log("left key pressed");
        moveXPos = xPos - appShowSize;
        moveYPos = yPos;
        break;
    case SDLK_RIGHT:

        SDL_Log("right key pressed");
        moveXPos = xPos + appShowSize;
        moveYPos = yPos;
        break;
    default:
        // 不处理其他按键
        return 0;
    }

    // 根据坐标拿到当前点的属性
    int canMove = 0;
    itemId = floor_1[moveYPos / appShowSize][moveXPos / appShowSize];
    if (itemId == 4) {

        // 墙
    } else if (itemId == 3) {

        // 地面
        canMove = 1;
    } else if (itemId == 0 || itemId == 1 || itemId == 2) {

        // 钥匙
        canMove = 1;
        // 道具吃掉了,默认变成地面
        floor_1[moveYPos / appShowSize][moveXPos / appShowSize] = 3;
    }  else if (itemId == 5 || itemId == 6 || itemId == 7) {

        // 门
        canMove = 1;
        floor_1[moveYPos / appShowSize][moveXPos / appShowSize] = 3;
    } else if (itemId == 8 || itemId == 9 || itemId == 10) {

        // 宝石
        canMove = 1;
        floor_1[moveYPos / appShowSize][moveXPos / appShowSize] = 3;
    } else if (itemId == 11 || itemId == 12 || itemId == 13 || itemId == 14) {

        // 药水
        canMove = 1;
        floor_1[moveYPos / appShowSize][moveXPos / appShowSize] = 3;
    } else if (itemId == 16 || itemId == 17) {

        canMove = 1;
    }

    if (canMove) {

        switch (keyCode)
        {
        case SDLK_UP:

            yPos -= appShowSize;
            break;
        case SDLK_DOWN:

            yPos += appShowSize;
            break;
        case SDLK_LEFT:

            xPos -= appShowSize;
            break;
        case SDLK_RIGHT:

            xPos += appShowSize;
            break;
        default:
            break;
        }
    }

    // SDL_Log("key pressed item %d", itemId);
    return 0;
}

int mapResource::renderMap(SDL_Renderer* renderer) {

    // 背景先统一置为地面
    for (int i = 0; i < 13; i++) {

        for (int j = 0; j < 13; j++) {

            SDL_Rect destRect = { i * appShowSize, j * appShowSize, appShowSize, appShowSize };
            SDL_RenderCopy(renderer, texture[3], NULL, &destRect);
        }
    }

    // 然后绘制地图上的item
    for (int i = 0; i < 13; i++) {

        for (int j = 0; j < 13; j++) {

            SDL_Rect destRect = { i * appShowSize, j * appShowSize, appShowSize, appShowSize };
            // 显示方式是一行一行显示的,所以行先不动,遍历所有的列
            SDL_RenderCopy(renderer, texture[floor_1[j][i]], NULL, &destRect);
        }
    }

    SDL_Rect moveRect = { xPos, yPos, appShowSize, appShowSize };

    SDL_RenderCopy(renderer, texture[15], NULL, &moveRect);
    return 0;
}

// g++ map.cpp -lSDL2 -lSDL2_image
int main(int argc, char* argv[]) {

    int WINDOW_WIDTH = X_BLOCK_NUM * BLOCK_WIDTH;
    int WINDOW_HEIGHT = Y_BLOCK_NUM * BLOCK_HEIGHT;

    int imgFlags = IMG_INIT_PNG;

    SDL_Window* window = nullptr;
    SDL_Renderer* renderer = nullptr;
    SDL_Surface *buttonSurface = nullptr;
    SDL_Texture *buttonTexture = nullptr;
    mapResource mapResource;

    // 事件循环
    SDL_Event event;
    bool quit = false;

    static const int MIN_FRAME_TIME = 16;
    Uint32 frameTime = 0;

    bool isMouseRelease = true;
    bool isTouchRelease = true;

    // 初始化SDL
    if (SDL_Init(SDL_INIT_VIDEO) != 0) {
        SDL_Log("Failed to initialize SDL: %s", SDL_GetError());
        return 1;
    }

    SDL_Rect gScreenRect = { 0, 0, 320, 240 };
    SDL_DisplayMode displayMode;
    if( SDL_GetCurrentDisplayMode( 0, &displayMode ) == 0 )
    {
        gScreenRect.w =  displayMode.h;
        gScreenRect.h =  displayMode.w;
    }

    // appShowSize =  gScreenRect.w / X_BLOCK_NUM;
    appShowSize = 32 * 1;
    SDL_Rect upBotton       = {appShowSize * 4, appShowSize * 14, appShowSize * 4, appShowSize * 2};
    SDL_Rect downBotton     = {appShowSize * 4, appShowSize * 18, appShowSize * 4, appShowSize * 2};
    SDL_Rect leftBotton     = {appShowSize * 1, appShowSize * 16, appShowSize * 4, appShowSize * 2};
    SDL_Rect rightBotton    = {appShowSize * 7, appShowSize * 16, appShowSize * 4, appShowSize * 2};


    // 创建窗口
    window = SDL_CreateWindow("Magic Tower", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, gScreenRect.w, gScreenRect.h, SDL_WINDOW_SHOWN);
    if (window == nullptr) {

        SDL_Log("Failed to create window: %s", SDL_GetError());
        goto end;
    }

    // 创建渲染器
    renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
    if (renderer == nullptr) {
        SDL_Log("Failed to create renderer: %s", SDL_GetError());
        goto end;
    }

    // 初始化SDL_image
    if (!(IMG_Init(imgFlags) & imgFlags)) {
        SDL_Log("Failed to initialize SDL_image: %s", IMG_GetError());
        goto end;
    }

    mapResource.initResource(renderer);
    mapResource.xPos = appShowSize * 5;
    mapResource.yPos = 0;

    buttonSurface = IMG_Load("tiled/button.png");
    if (buttonSurface == nullptr) {

        SDL_Log("Failed to  button: %s", IMG_GetError());
        goto end;
    }

    buttonTexture = SDL_CreateTextureFromSurface(renderer, buttonSurface);
    if (buttonTexture == nullptr) {
        SDL_Log("Failed to create texture: %s", SDL_GetError());
        goto end;
    }

    while (!quit) {

        SDL_RenderClear(renderer);

        // 背景填充颜色
        // SDL_SetRenderDrawColor(renderer, 93, 148, 252, 255);
        // SDL_RenderClear(renderer);

        frameTime = SDL_GetTicks();
        SDL_Keycode keyCode = SDLK_UNKNOWN;
        while (SDL_PollEvent(&event)) {

            if (event.type == SDL_QUIT) {
                quit = true;
            } else if (event.type == SDL_KEYDOWN) {

                // 按键按下
                keyCode = event.key.keysym.sym;
            } else if (event.type == SDL_MOUSEBUTTONDOWN || event.type == SDL_FINGERDOWN) {

                SDL_Log("state = %d\n", event.button.state);
                if (event.type == SDL_MOUSEBUTTONDOWN && event.button.state == SDL_PRESSED) {

                    isMouseRelease = false;
                    SDL_Log("mouse press");
                } else if (event.type == SDL_MOUSEBUTTONDOWN && event.button.state == SDL_RELEASED) {
                    
                    SDL_Log("mouse realse");
                    isMouseRelease = true;
                } else if (event.type == SDL_FINGERDOWN) {

                    isTouchRelease = false;
                    SDL_Log("finger press");
                } else if (event.type == SDL_FINGERUP) {
                    isTouchRelease = true;
                    SDL_Log("finger leave"); 
                }
            }
        }

        // 检测鼠标点击位置是否在按钮内
        int mouseX= 0, mouseY = 0;
        if (!isMouseRelease) {

            SDL_GetMouseState(&mouseX, &mouseY);
        } else if (!isTouchRelease) {

            mouseX = event.tfinger.x;
            mouseY = event.tfinger.y;
        }

        if (mouseX >= upBotton.x && mouseX <= upBotton.x + upBotton.w &&
            mouseY >= upBotton.y && mouseY <= upBotton.y + upBotton.h) {
            
            keyCode = SDLK_UP;
        } else if (mouseX >= downBotton.x && mouseX <= downBotton.x + downBotton.w &&
            mouseY >= downBotton.y && mouseY <= downBotton.y + downBotton.h) {
            
            keyCode = SDLK_DOWN;
        } else if (mouseX >= leftBotton.x && mouseX <= leftBotton.x + leftBotton.w &&
            mouseY >= leftBotton.y && mouseY <= leftBotton.y + leftBotton.h) {
            
            keyCode = SDLK_LEFT;
        } else if (mouseX >= rightBotton.x && mouseX <= rightBotton.x + rightBotton.w &&
            mouseY >= rightBotton.y && mouseY <= rightBotton.y + rightBotton.h) {
            
            keyCode = SDLK_RIGHT;
        }

        mapResource.isCollisions(keyCode);
        mapResource.renderMap(renderer);

        SDL_RenderCopy(renderer, buttonTexture, NULL, &upBotton);
        SDL_RenderCopy(renderer, buttonTexture, NULL, &downBotton);
        SDL_RenderCopy(renderer, buttonTexture, NULL, &leftBotton);
        SDL_RenderCopy(renderer, buttonTexture, NULL, &rightBotton);
        // 显示固定图层
        SDL_RenderPresent(renderer);

        if(SDL_GetTicks() - frameTime < MIN_FRAME_TIME) {
			SDL_Delay(MIN_FRAME_TIME - (SDL_GetTicks () - frameTime));
		}
    }

    // 清理资源
    // SDL_DestroyTexture(imageTexture);
    // SDL_DestroyTexture(imageTexture1);
    // SDL_FreeSurface(imageSurface);
    // IMG_Quit();
    // SDL_DestroyRenderer(renderer);
    // SDL_DestroyWindow(window);
    // SDL_Quit();

end:
    // if (blueKeyTexture)
    //     SDL_DestroyTexture(blueKeyTexture);
    
    // if (readKeyTexture)
    //     SDL_DestroyTexture(readKeyTexture);
    
    // if (imageSurface) {
    //      SDL_FreeSurface(imageSurface);
    // }

    if (window)
        SDL_DestroyWindow(window);
    
    if (renderer)
        SDL_DestroyRenderer(renderer);

    SDL_Quit();

    return 0;
}